package org.ldx.lotterysystem.common.utils;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

//这是一个redis操作类
@Slf4j
@Configuration
public class RedisUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public boolean set(String key,String value){
        try{
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e){
            log.error("redis设置值出错：",e);
            return false;
        }
    }

    /**
     * 可设置过期时间的set方法
     * @param key
     * @param value
     * @param time 单位为秒
     * @return
     */
    public boolean set(String key,String value,Long time){
        try{
            stringRedisTemplate.opsForValue().set(key, value,time,TimeUnit.SECONDS);//最后一个参数表示单位为秒
            return true;
        }catch (Exception e){
            log.error("redis set {} error",key,e);
            return false;
        }
    }
    public String get(String key){
        try{
            return StringUtils.hasText(key)?
                    stringRedisTemplate.opsForValue().get(key):null;
        }catch (Exception e){
            log.error("redis get {} error:",key,e);
            return null;
        }
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public boolean del(String... key){
        try{
            if(key != null&&key.length>0){
                if(key.length == 1){
                    stringRedisTemplate.delete(key[0]);
                }else {
                    stringRedisTemplate.delete(
                            (Collection<String>) CollectionUtils.arrayToList(key)
                    );
                }
            }

            return true;
        }catch (Exception e){
            log.error("redis del {} error",key,e);
            return false;
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try{
            return StringUtils.hasText(key)?stringRedisTemplate.hasKey(key)
                    :false;
        }catch (Exception e){
            log.error("redis del {} error",key,e);
            return false;
        }

    }
}
